(function (ctx,factory) {
    var nameSpace = 'field_7827871416804946708';
    if(!window[nameSpace]){
        var Builder = factory(ctx,nameSpace);
        window[nameSpace] = {
            instance: {}
        };
        window[nameSpace].init = function (options) {
            window[nameSpace].instance[options.privateId] = new Builder(options);
        };
    }
})(typeof $ === 'undefined' ? top.$ : $,function($,domain){

    function App(options) {
        var self = this;
        //初始参数
        self.initParams(options);
        //初始DOM
        self.initDom();
        //事件
        self.events();
    }

    App.prototype.initParams = function (options) {
        var self = this;
        self.adaptation = options.adaptation;
        self.privateId = options.privateId;
        self.messageObj = options.getData;
        self.auth = self.messageObj.auth;
        self.isNotNull = self.messageObj.isNotNull;
        self.content = self.messageObj.formdata.content || {};
        self.attachmentInfo = self.messageObj.attachmentInfo;

        self.formId = self.content.contentTemplateId;
        self.fieldName = self.messageObj.id;
        self.formMessage = options.formMessage;
        self.formDataId = self.content.contentDataId;
        self.formSubDataId = self.messageObj.recordId;
        self.rightId = self.content.rightId;
        if(self.messageObj.customFieldInfo.customParam==null){
            $.alert($.i18n("com.cap.ctrl.ocr.running.noset",self.messageObj.display));
            return;
        }
        self.fieldDefine = self.messageObj.customFieldInfo.customParam.mapping;
    };

    App.prototype.initDom = function () {
        var self = this;
        self.container = $(document.getElementById(self.privateId));

        var html = '<section class="cap4-images is-one"><div class="cap4-images__left">' + self.messageObj.display + '</div><div class="cap4-images__right"><div class="cap4-images__cnt" style="min-height: 30px;border: 1px solid #d4d4d4;border-radius: 4px;"><div class="cap4-images__items"><div class="cap4-images__holder"></div></div><div class="cap4-images__picker upload ' + self.privateId + '"><div class="icon CAP cap-icon-credentials-recognition"></div></div></div></div></section>';
        self.container.html(html);

        if(self.attachmentInfo && self.attachmentInfo.attachmentInfos && self.attachmentInfo.attachmentInfos.length !== 0){
            var attachment = self.attachmentInfo.attachmentInfos[0];
            self.attachmentId = attachment.id;
            var opts = {
                createDate: attachment.createDate,
                fileId: attachment.fileUrl,
                filename: attachment.filename,
                v: attachment.v
            };
            var imgUrl = (_ctxPath ? _ctxPath : '/seeyon') + '/fileDownload.do?method=download&' + parseParam(opts);
            var imgDom = '<div class="cap4-images__it"><a href="' + imgUrl + '">' + attachment.filename + '</a><div class="cap4-images__close"><i class="icon CAP cap-icon-guanbi delete"></i></div></div>';
            var imgContainer = self.container.find(".cap4-images__holder");
            imgContainer.html(imgDom);
            self.container.find(".upload").css("display", "none");
        }

        self.renderIsMust();

        //渲染隐藏
        if(self.auth === 'hide'){
            self.container.find('.cap4-images__right').html('<div class="cap4-text__browse" style="line-height: 1.8; color: rgb(0, 0, 0) !important;">***</div>')
        }

        //PC端不显示标题
        self.container.find(".cap4-images__left").css("display","none");
        self.container.find(".cap4-images__right").css("margin-left","0");

        if(self.auth === 'browse'){
            self.container.find(".cap4-images__cnt").css("border","none");
            self.container.find(".cap4-images__cnt").css("background","none");
            self.container.find(".upload").css("display", "none");
            self.container.find(".cap4-images__close").css('display','none');
        }
    };

    App.prototype.events = function () {
        var self = this;

        if(self.auth === 'browse')
            return;

        //上传附件按钮
        self.container.off('click','.upload.' + self.privateId).on('click', '.upload.' + self.privateId, function () {
            var options = {
                type: 0,
                firstSave: true,
                applicationCategory: 66,
                extensions: 'bmp,jpg,jpeg,png',
                maxSize: '',
                isEncrypt: '',
                popupTitleKey: '',
                attachmentTrId: 'Att',
                takeOver: 'false',
                quantity: 1
            };
            $.ajax({url: '/seeyon/rest/cap4/ocrCustom/getToken',
            	success: function (data) {
            		options.CSRFTOKEN = top.CsrfGuard.getToken();//data.data;
            		options.callMethod = domain + '.instance.' + self.privateId + '.uploadOcrCallback';
                    var url = (_ctxPath ? _ctxPath : '/seeyon') + '/fileUpload.do?' + parseParam(options);
                    getCtpTop().addattachDialog = null;
                    getCtpTop().addattachDialog = getCtpTop().$.dialog({
                        title: $.i18n('fileupload.page.title'),
                        transParams: {
                            parentWin: window
                        },
                        url: url,
                        width: 400,
                        height: 250
                    });
                },
                error: function (e) {
                }
            });
        });
        //附件清除按钮
        self.container.off('click', '.delete').on('click', '.delete', function () {
            self.container.find(".cap4-images__holder").empty();
            self.container.find(".upload").css("display", "block");

            /*
            var renderFields = [];
            $.each(self.fieldDefine.subPropMapping,function (index,item) {
                var main = {},target = main[item.target] = {};
                target.showValue = '';
                target.showValue2 = '';
                target.value = '';
                renderFields.push(main);
            });
            self.renderFormData(renderFields);
            */

            self.renderIsMust();

            //删除附件
            var attData = {
                tableName : self.formMessage.tableName,
                tableCategory : self.formMessage.tableCategory,
                updateRecordId : self.formSubDataId,
                handlerMode : 'delete',
                fieldName : self.fieldName,
                deleteAttchmentData : [self.attachmentId]
            };
            self.adaptation.backfillFormAttachment(attData,self.privateId);
        });
        //监听数据变化
        self.adaptation.ObserverEvent.listen('Event' + self.privateId, function () {
            self.messageObj = self.adaptation.childrenGetData(self.privateId);
            self.isNotNull = self.messageObj.isNotNull;
            self.auth = self.messageObj.auth;
            self.attachmentInfo = self.messageObj.attachmentInfo;

            self.initDom();
        });
    };

    //附件上传完成后回调
    App.prototype.uploadOcrCallback = function (atts) {
        var self = this;
        var attachment = atts.instance[0];
        var opts = {
            createDate: attachment.createDate,
            fileId: attachment.fileUrl,
            filename: attachment.filename,
            v: attachment.v
        };
        var imgUrl = (_ctxPath ? _ctxPath : '/seeyon') + '/fileDownload.do?method=download&' + parseParam(opts);
        var imgDom = '<div class="cap4-images__it"><a href = "' + imgUrl + '">' + attachment.filename + '</a><div class="cap4-images__close"><i class="icon CAP cap-icon-guanbi delete"></i></div></div>';

        var imgContainer = self.container.find(".cap4-images__holder");
        imgContainer.html(imgDom);
        self.container.find(".upload").css("display", "none");

        self.renderIsMust();

        //上传附件
        attachment.reference = self.attachmentInfo.baseAttachmentInfo.reference;
        attachment.subReference = self.attachmentInfo.baseAttachmentInfo.subReference;
        var attData = {
            tableName : self.formMessage.tableName,
            tableCategory : self.formMessage.tableCategory,
            updateRecordId : self.formSubDataId,
            handlerMode : 'add',
            fieldName : self.fieldName,
            addAttchmentData : atts.instance
        };
        self.attachmentId = attachment.id;
        self.adaptation.backfillFormAttachment(attData,self.privateId);

        //调用后台rest处理结果
        var fileId = attachment.fileUrl;
        var process = top.$.progressBar({
            text: $.i18n('com.cap.ctrl.ocr.running.parsing')
        });
        $.ajax({
            url: '/seeyon/rest/cap4/ocrCustom/recognition?formId=' + self.formId + '&fieldName=' + self.fieldName + '&fileId=' + fileId + '&formDataId=' + self.formDataId + '&formSubDataId=' + self.formSubDataId + '&rightId=' + self.rightId,
            success: function (data) {
                process.close();
                var renderData = data.data;
                if(renderData)
                    self.renderFormData(renderData);
            },
            error: function (e) {
                process.close();
                var error = JSON.parse(e.responseText);
                if(error.message){
                    top.$.error(error.message);
                }else{
                    top.$.error($.i18n('com.cap.ctrl.ocr.running.parsingerror'));
                }

            }
        });
    };

    /**
     * 回填表单
     * @param data
     */
    App.prototype.renderFormData = function (data) {
        if(!data || !(data instanceof Array))
            return;
        var self = this;
        var lists = [];
        $.each(data,function (index,item) {
            var obj = {
                tableName : self.formMessage.tableName,
                tableCategory : self.formMessage.tableCategory,
                updateRecordId : self.formSubDataId,
                updateData : item
            };
            lists.push(obj);
        });
        self.adaptation.backfillFormControlData(lists,self.privateId);
    };

    /**
     * 刷新必填样式
     */
    App.prototype.renderIsMust = function () {
        var self = this;
        if(self.isNotNull === '1' && self.auth !== 'browse' && !self.container.find(".cap4-images__holder").html()){
            self.container.find('section').addClass('is-must');
        }else{
            self.container.find('section').removeClass('is-must');
        }
    };

    var parseParam = function (param, key) {
        var paramStr = "";
        if (param instanceof String || param instanceof Number || param instanceof Boolean) {
            paramStr += "&" + key + "=" + encodeURIComponent(param);
        } else {
            $.each(param, function (i) {
                var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
                paramStr += '&' + parseParam(this, k);
            });
        }
        return paramStr.substr(1);
    };

    return App;
});
